from typing import Dict
from pathlib import Path
import logging
from core.translation_interface import TranslationEngine
from core.asr_engine import ASREngine
from core.translation_engine import TranslationEngine as TextTranslationEngine

logger = logging.getLogger(__name__)

class WhisperMarianAdapter(TranslationEngine):
    """
    Whisper ASR + MarianMT 翻译的适配器
    实现分步处理：音频 -> 文本 -> 翻译
    """
    
    def __init__(self):
        self.asr_engine = ASREngine()
        self.translation_engine = TextTranslationEngine()
        
    def translate_audio(
        self, 
        audio_path: str, 
        source_lang: str, 
        target_lang: str,
        enable_translation: bool = True,
        return_segments: bool = False
    ) -> Dict:
        """分步处理：ASR + 文本翻译"""
        
        try:
            # 1. ASR 识别
            if not self.asr_engine.is_ready():
                raise RuntimeError("ASR引擎未就绪")
                
            asr_result = self.asr_engine.transcribe(
                Path(audio_path), 
                language=source_lang,
                return_segments=return_segments
            )
            
            source_text = asr_result.get("text", "").strip()
            if not source_text:
                return {
                    "text": "",
                    "translated_text": "",
                    "confidence": 0.0,
                    "duration": asr_result.get("duration", 0.0),
                    "segments": asr_result.get("segments", [])
                }
            
            # 2. 文本翻译
            if enable_translation:
                trans_result = self.translation_engine.translate(
                    source_text, 
                    source_lang=source_lang, 
                    target_lang=target_lang
                )
                translated_text = trans_result.get("translated_text", "")
                confidence = trans_result.get("confidence", 0.9)
            else:
                translated_text = source_text
                confidence = 0.9
            
            return {
                "text": source_text,
                "translated_text": translated_text,
                "confidence": confidence,
                "duration": asr_result.get("duration", 0.0),
                "segments": asr_result.get("segments", []) if return_segments else []
            }
            
        except Exception as e:
            logger.error(f"WhisperMarianAdapter翻译失败: {e}")
            raise
    
    def is_ready(self) -> bool:
        """检查两个引擎是否都就绪"""
        return self.asr_engine.is_ready() and self.translation_engine.is_ready()
    
    def get_supported_languages(self) -> Dict[str, list]:
        """获取支持的语言列表"""
        return {
            "asr_languages": ["zh", "en", "ja", "ko", "fr", "de", "es", "ru"],
            "translation_languages": ["zh", "en", "ja", "ko", "fr", "de", "es", "ru"]
        }




